const express = require('express');
const db = require('../mongodb/db');
const articleModel = require('../mongodb/models/articleModel');
const adminModel = require('../mongodb/models/adminModel');
const jieba = require('nodejieba');
// const articleDetailModel = require('../mongodb/models/articleDetail');
var router = express.Router();
const config=require('../mongodb/config')
db(() => {

})

/* GET users listing. */
router.get('/article', async function (req, res, next) {
    const page = parseInt(req.query.page) || 1;
    const limit = 3;
    const skip = (page - 1) * limit;
    const total=await articleModel.countDocuments({})
    try {
        const data = await articleModel.find().sort({ time: -1 }).skip(skip).limit(limit);

        let promises = data.map(async item => {

            //返回封面图片路径
            const num = Math.floor(Math.random() * 42 + 1)

            let adminInfo = await adminModel.findOne({ _id: item.uid });

            // 浅拷贝对象，避免修改原始数据
            let newItem = { ...item._doc };

            delete newItem.text;  
            // delete newItem.mdText;  
            newItem.userName = adminInfo.userName;  
            newItem.avatar = adminInfo.avatar;
            newItem.src = `http://${config.IP}:${config.hPort}/public/pic/pic${num}.avif` ;
            return newItem;
        });

        const processedData = await Promise.all(promises);

        res.json({
            code: '000',
            msg: '获取文章列表成功',
            list: processedData,
            total:total
        });
    } catch (error) {
        res.status(500).send('获取文章列表失败');
    }
});

router.post('/article', function (req, res, next) {
    // const titleKeywords = jieba.cut(req.body.title, true);
    let titleKeywords = jieba.cut(req.body.title, true).reduce((acc, word) => {
        acc.push(word); // 保留原单词
        if (/^[a-zA-Z]+$/.test(word)) {
            acc.push(word.toLowerCase()); // 添加小写版本
        }
        return acc;
    }, []);

    let listData={
        title:req.body.title,
        time:req.body.time,
        uid:req.body.uid,
        text:req.body.text,
        mdText:req.body.mdText,
        introduce:req.body.introduce,
        keyWords:titleKeywords
    }
   articleModel.create(listData)
   .then(data=>{
          res.json({
              code: '000',
              msg: '提交成功',
              data: data
          })
   })
   .catch(err=>{
           if (err) {
               return res.status(500).send('提交失败')
           }
   })
    
    })

router.get('/aDetail', function (req, res, next) {
   
    articleModel.findOne({_id:req.query.aId})
    .then(data=>{
        adminModel.findOne({ _id: data.uid })
        .then(aData=>{
                res.json({
                    code:'000',
                    msg:'获取详情页成功',
                    list:{
                        time: data.time,
                        title: data.title,
                        text: data.text,
                        // mdText:data.mdText,
                        introduce: data.introduce,
                        avatar: aData.avatar,
                        userName: aData.userName
                    }
                })
        })
        .catch(err=>{
            if (err) {
                    res.status(500).send('获取作者信息失败')
                    return
                }
        })
    })
    .catch(ERR=>{
        if (ERR) {
            return res.status(500).send('获取文章详情失败')
        }
    })
        // if (err) {
        //     return res.statusCode(500).send('获取文章详情失败')
        // }
        // adminModel.findOne({_id:data.uid},(err,aData)=>{
        //     if (err) {
        //         res.status(500).send('获取作者信息失败')
        //         return
        //     }
        //     res.json({
        //         code:'000',
        //         msg:'获取详情页成功',
        //         time:data.time,
        //         title:data.title,
        //         text:data.text,
        //         avatar:aData.avatar,
        //         username:aData.username
        //     })
        // })
   
})
router.post('/edify', function (req, res, next) {
    let listData = {
        title: req.body.title,
        text: req.body.text,
        mdText:req.body.mdText,
        introduce: req.body.introduce,
    }
    articleModel.updateOne({_id:req.body.aId},listData)
    .then(data=>{
        res.json({
            code: '000',
            msg: '修改成功',
            data: data
        })
    })
    .catch(err=>{
        if (err) {
            return res.status(500).send('修改失败')
        }
    })
        // if (err) {
        //     return res.status(500).send('修改失败')
        // }
        // res.json({
        //     code: '000',
        //     msg: '修改成功',
        //     data: data
        // })
   
})

router.delete('/delete', function (req, res, next) {

    articleModel.deleteOne({ _id: req.query.aId })
    .then(data=>{
        res.json({
            code: '000',
            msg: '删除成功',
            data: data
        })
    })
    .catch(err=>{
        if (err) {
            return res.status(500).send('删除失败')
        }
    })
        // if (err) {
        //     return res.statusCode(500).send('删除失败')
        // }
        // res.json({
        //     code: '000',
        //     msg: '删除成功',
        //     data: data
        // })
  
})

router.get('/myArticle', async function (req, res, next) {
    const page = parseInt(req.query.page) || 1;
    const limit = 3;
    const skip = (page - 1) * limit;
    const total = await articleModel.countDocuments({ uid: req.query.uid })
    try {
        const data = await articleModel.find({uid:req.query.uid}).sort({ time: -1 }).skip(skip).limit(limit);
        // const { userName, avatar } = await adminModel.findOne({ _id: req.query.uid })
        let promises = data.map(item => {
            const num = Math.floor(Math.random() * 42 + 1)
            // 浅拷贝对象，避免修改原始数据
            let newItem = { ...item._doc };
            newItem.src = `http://${config.IP}:${config.hPort}/public/pic/pic${num}.avif`;
            delete newItem.text;
            // delete newItem.mdText; 
            return newItem;
        });
        // const resolvedList = await Promise.all(promises);
        res.json({
            code: '000',
            msg: '获取我的文章列表成功',
            list: promises,
            total:total
            // userName:userName,
            // avatar:avatar
        });
    } catch (error) {
        res.status(500).send('获取我的文章列表失败');
    }

});

router.get('/search',async(req,res,next)=>{
    const key=req.query.keyWord
    const page = parseInt(req.query.page) || 1;
    const limit = 3;
    const skip = (page - 1) * limit;
    const total = await articleModel.find({ keyWords: { $in: key } }).countDocuments({})
    try{
        const result = await articleModel.find({ keyWords: { $in: key } }).sort({ time: -1 }).skip(skip).limit(limit)

        let promises = result.map(async item => {
            const num = Math.floor(Math.random() * 42 + 1)

            let adminInfo = await adminModel.findOne({ _id: item.uid });
            // 浅拷贝对象，避免修改原始数据
            let newItem = { ...item._doc };
            delete newItem.text;
            // delete newItem.mdText; 
            newItem.userName = adminInfo.userName;
            newItem.avatar = adminInfo.avatar;
            newItem.src = `http://${config.IP}:${config.hPort}/public/pic/pic${num}.avif`;
            return newItem;
        });
        // 多个异步操作要全部结束才传数据
        const processedData = await Promise.all(promises);

        res.json({
            code:'000',
            msg:'关键词搜索成功',
            searchList: processedData,
            total:total
        })

    }catch(err){
        res.status(500).send('关键词搜索失败');
    }
})
module.exports = router;